$(document).ready(function() {

    initFindOrderInput();
    initConfirmOrderButton();
    initBookCountInput();

    $('.digit').forceNumericOnly();
})

function refreshTotalSum(order){
    var totalSum = 0
    var totalCount = order.bookList.length
    $.each(order.bookList, function(i, book){
        totalSum += book.price
    })
    $('#totalCount').text(totalCount)
    $('#totalSum').text(totalSum)
}

function deleteBook(element){
    if (typeof element === 'undefined' || typeof element.id === 'undefined'){
        return
    }
    var bookId = element.id.replace('book-delete-button-','')

    var bookName = $('#book-name-' + bookId).text()
    var bookPrice = $('#book-price-' + bookId).text()
    var book = {}
    book.bookId = bookId
    book.name = bookName
    book.price = bookPrice

    $.ajax({
        type: "post",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(book),
        url: "removeBooksFromCart.htm",
        success: function(order) {
            $('tr#book-row-' + bookId).remove()
            initConfirmOrderButton()
            refreshTotalSum(order);
        },
        error: function(aa) {
            alert("error data = " + aa)
        }
    })
}

function initFindOrderInput(){
    $('#find-order-input').on('keypress',function(e){
        if (e.which == 13){
            var orderId = $(this).val();
            if (orderId === ''){return}
            $.ajax({
                type: "post",
                dataType: "html",
                data: {'orderId': orderId},
                url: "findOrder.htm",
                success: function(order) {

                    $('#find-order-container').html(order)
                },
                error: function(aa) {
                    alert("error data = " + aa)
                }
            })
        }
    })
    if ($('#find-order-input').val() === ''){
        $('#find-order-input')
            .val('Введите номер заказа')
            .addClass('default-text')
    }
    $('#find-order-input').on('blur', function(){
        if ($('#find-order-input').val() === ''){
            $('#find-order-input')
                .val('Введите номер заказа')
                .addClass('default-text')
        }
    })

    $('#find-order-input').on('focus', function(){
        if ($('#find-order-input').val() === 'Введите номер заказа'){
            $('#find-order-input')
                .val('')
                .removeClass('default-text')
        }
    })
}

function addToCart(element){
    if (typeof element === 'undefined' || typeof element.id === 'undefined'){
        return
    }
    var bookId = element.id.replace('add-to-cart-button-','')
    var bookName = $('#book-name-' + bookId).text()
    var bookPrice = $('#book-price-' + bookId).text()
    var book = {}
    book.bookId = bookId
    book.name = bookName
    book.price = bookPrice

    $.ajax({
        type: "post",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(book),
        url: "addToCart.htm",
        success: function(order) {
            if (order.bookList.length !== 0){
                $('#cart').load('../jsp/app/template/cartTemplate.jsp', order, function(){

                })
            }
        },
        error: function(aa) {
            alert("error data = " + aa)
        }
    })
}

function initConfirmOrderButton(){
    $('#confirm-order-form input[type=text]').length > 0
        ? $('#confirm-order-button').removeAttr('disabled')
        : $('#confirm-order-button').attr('disabled', 'disabled')
}

// Numeric only control handler
jQuery.fn.forceNumericOnly =
    function()
    {
        return this.each(function()
        {
            var input = $(this)
            var isCtrl = false
            $(this).on('keydown', function(e){
                var key = e.charCode || e.keyCode || 0;
                // allow enter, backspace, tab, delete, arrows, home, end, ctrl + c, ctrl + v,  numbers and keypad numbers ONLY
                var vKey = 86, cKey = 67, xKey=120;
                return (
                    key == 8 ||
                        key == 9 ||
                        key == 13 ||
                        key == 35 ||
                        key == 36 ||
                        key == 46 ||
                        (key >= 37 && key <= 40) ||
                        (key >= 48 && key <= 57) ||
                        (key >= 96 && key <= 105) ||
                        (e.ctrlKey && key == vKey) ||
                        (e.ctrlKey && key == cKey) ||
                        (e.ctrlKey && key == xKey)
                    );
            }).on('paste', function(e){
                var lastVal = $(this).val()
                setTimeout(function(){
                    var newValue = input.val()
                    if (isNaN(newValue)){
                        input.val(lastVal)
                    }
                }, 1);
            });
        });
    };

function initBookCountInput(){
    $('input[id*="book-count-input-"]').on('blur', function(){
        if (this.value == '' || parseInt(this.value) < 1){
            this.value = '1'
        }
        var data = {}
        var bookId = this.id.replace('book-count-input-','')
        var bookName = $('#book-name-' + bookId).text();
        var bookPrice = $('#book-price-' + bookId).text();
        var countBook = parseInt(this.value)
        data.bookList = []
        for (var i = 0; i < countBook; i++){
            data.bookList.push({'bookId': bookId, 'name':bookName, 'price': bookPrice})
        }
        $.ajax({
            type: "post",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            url: "changeCountBookCart.htm",
            success: function(order) {
                refreshTotalSum(order)
            },
            error: function(aa) {
                alert("error data = " + aa)
            }
        })
    })
}